package cn.itcast.usermanager.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;



import cn.itcast.manager.service.UserService;
import cn.itcast.usermanager.pojo.EasyUIResult;
import cn.itcast.usermanager.pojo.User;


@RequestMapping("user")
@Controller
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="user")
	public String test1() {
		return "users";
	}
	
	@ResponseBody
	@RequestMapping(value="list")
	public EasyUIResult easyUIResult(@RequestParam("page")Integer pageNum,
			@RequestParam("rows")Integer pageSize) {
		
		return this.userService.queryPage(pageNum,pageSize);
	}
	
	@RequestMapping(value="page/{aaa}")
	public String addUser(@PathVariable("aaa")String aaa) {
		
		
		return aaa;
	}
	
	@RequestMapping("save")
	@ResponseBody
	public Map<String,Object> addUser1(User user) {
		Map<String,Object> map = new HashMap<>();
		try {
			Boolean b = this.userService.addUser(user);
			if (b) {
				map.put("status", "200");
			}else{
				map.put("status", "500");
			}
			
		} catch (Exception e) {
			map.put("status", "500");
			e.printStackTrace();
		}
		
		return map;
	}
	
	@RequestMapping("update")
	@ResponseBody
	public Map<String,Object> updateUser(User user) {
		Map<String,Object> map = new HashMap<>();
		
		try {
			Boolean b = this.userService.updateUser(user);		
			if (b) {
				map.put("status", "200");
			}else {
				map.put("status", "500");
			}
			
		} catch (Exception e) {
			map.put("status", "500");
			e.printStackTrace();
		}
		
		return map;
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public Map<String,Object> deleteUser(@RequestParam("ids")String[] ids) {
		Map<String, Object> map = new HashMap<>();
		
		try {
			Boolean b = this.userService.deleteUser(ids);
			if (b) {
				map.put("status", "200");
			}else {
				map.put("status", "500");
			}
			
		} catch (Exception e) {
			map.put("put", "500");
			e.printStackTrace();
		}
		
		
		return map;
	}
	
	@RequestMapping("export/excel")
	public String exportExcel(Model model,@RequestParam("page")Integer pageNum,@RequestParam("rows")
	Integer pageSize) {
		EasyUIResult easyUIResult = this.userService.queryPage(pageNum, pageSize);
		model.addAttribute("userList", easyUIResult.getRows());
		
		return "userExcelView";
	}
}
